package com.cxg.fairy.ec.main.index.ad;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.cxg.fairy.app.AccountManager;
import com.cxg.fairy.app.Latte;
import com.cxg.fairy.delegates.LatteDelegate;
import com.cxg.fairy.delegates.bottom.BottomItemDelegate;
import com.cxg.fairy.delegates.web.WebDelegateImpl;
import com.diabin.latte.ec.R;
import com.diabin.latte.ec.R2;

import butterknife.OnClick;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

import static com.cxg.fairy.app.Latte.getApplicationContext;

/**
 * Created by CFairy
 */

public class ADGoodsHtmlDelegate extends LatteDelegate {

    private WebView wb;

    private static final String ARG_GOODS_ID = "ARG_GOODS_ID";

    @Override
    public Object setLayout() {
        return R.layout.delegate_ad_goods_html;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
    }

    @OnClick(R2.id.back_home)
    void onClickBackHome() {
        getSupportDelegate().pop();
    }

    public static ADGoodsHtmlDelegate create(int goodsId) {
        final Bundle args = new Bundle();
        args.putInt(ARG_GOODS_ID, goodsId);
        final ADGoodsHtmlDelegate delegate = new ADGoodsHtmlDelegate();
        delegate.setArguments(args);
        return delegate;
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        final WebDelegateImpl delegate = WebDelegateImpl.create("http://api.c-fairy.net:8080/api-restservice/advertisement/index.html?uuid="+ AccountManager.getSignUUID()+"&templatePageId="+getArguments().getInt(ARG_GOODS_ID));
        delegate.setTopDelegate(this.getParentDelegate());
        getSupportDelegate().loadRootFragment(R.id.web_discovery_container, delegate);

        wb = delegate.getWebView();
        WebSettings ws = wb.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setJavaScriptCanOpenWindowsAutomatically(true);

        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        ws.setLoadWithOverviewMode(true);

        wb.addJavascriptInterface(new JSInterface(), "jsi");

    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultHorizontalAnimator();
    }

    @SuppressWarnings("unused")
    private final class JSInterface{
        @JavascriptInterface
        public void showToast(String text){
            Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
        }
        @JavascriptInterface
        public void showJsText(String text){
            wb.loadUrl("javascript:jsText('"+text+"')");
        }
    }
}
